package cn.hhhy.service.impl;

import cn.hhhy.mapper.User_VillageMapper;
import cn.hhhy.mapper.VillageMapper;
import cn.hhhy.pojo.PageResult;
import cn.hhhy.pojo.QueryPageBean;
import cn.hhhy.pojo.User_Village;
import cn.hhhy.pojo.Village;
import cn.hhhy.service.VillageService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class VillageServiceImpl implements VillageService {

    @Autowired
    private VillageMapper villageMapper;
    @Autowired
    private User_VillageMapper userVillageMapper;

//    分页查询
    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();

        IPage<Village> villageIPage = villageMapper.selectPage(new Page<>(currentPage,pageSize),
                Wrappers.lambdaQuery(Village.class)
                        .like(!Strings.isEmpty(queryString), Village::getVname, queryString)
                        .or()
                        .like(!Strings.isEmpty(queryString), Village::getVplace, queryString)
        );
        return new PageResult(villageIPage.getTotal(), villageIPage.getRecords());
    }

    @Override
    public Village findById(Integer id) {
        return villageMapper.selectById(id);
    }

    @Override
    public void delete(Integer id) {
        villageMapper.deleteById(id);
    }

    @Override
    public void update(Village village) {
        villageMapper.updateById(village);
    }

    @Override
    public void add(Village village) {
        villageMapper.insert(village);
    }

    @Override
    public List<Village> findAll() {
        return villageMapper.selectList(null);
    }

    @Override
    public List<Village> findByUID(Integer id) {
        List<User_Village> user_villages = userVillageMapper.selectList(Wrappers.lambdaQuery(User_Village.class)
                .eq(User_Village::getUid,id));

        List<Village> villages = new ArrayList<>();

        for (User_Village user_village : user_villages) {
            Village village = villageMapper.selectById(user_village.getVid());
            villages.add(village);
        }
        return villages;
    }
}
